<template>
  <Header :have_return_flg="true" :prePage="homePage" @stop-scan="handleCustomEvent">返回</Header> 
  <div>
    <video ref="video" autoplay playsinline style="width: 50%;"></video>
    <canvas ref="canvas" style="display: none;"></canvas>
    <!-- <button @click="goDetail">直接跳转</button> -->
    <p v-if="qrCodeData">扫描结果：{{ qrCodeData }}</p>
  </div>
</template>

<script>
import jsQR from "jsqr";
import Header from '../components/Header.vue'
export default {
  components: {
      Header
    },
  data() {
    return {
      videoStream: null,
      qrCodeData: null,
      scanning: true,
    };
  },
  async mounted() {
    // 获取摄像头视频流
    try {
        this.scanning = true;
        this.videoStream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: "environment" }, // 优先使用后置摄像头
        });
        this.$refs.video.srcObject = this.videoStream;

        // 等待视频加载完成
        this.$refs.video.onloadedmetadata = () => {
          this.scanQRCode();
        };
      } catch (error) {
        window.alert("摄像头访问失败：", error);
      }
  },
  methods: {
    handleCustomEvent(){
      this.stopScan()
    },
    scanQRCode() {
      if (!this.scanning) return;

      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");

      // 设置 canvas 尺寸与视频一致
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 每帧分析视频流
      const scan = () => {
        if (!this.scanning) return;

        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const qrCode = jsQR(imageData.data, canvas.width, canvas.height);

        if (qrCode) {

          this.qrCodeData = qrCode.data; // 获取二维码内容
          window.alert(this.qrCodeData)
          this.stopScan(); // 停止扫描
          // window.location.href = this.qrCodeData;
          this.$router.push({ name: "RestaurantDetail", params: { qrCodeData: this.qrCodeData } });
        } else {
          requestAnimationFrame(scan); // 继续下一帧
        }
      };

      scan();
    },
    stopScan() {
      if(this.scanning==true){
        this.scanning = false;
        if (this.videoStream) {
          this.videoStream.getTracks().forEach((track) => track.stop()); // 停止视频流
        }
      }
    },
    goDetail() {
      this.$router.push({ name: "RestaurantDetail", params: { qrCodeData: "xxxxxxxxxxxxxxxxxxx" } });

    },
  },
};
</script>

<style>
video {
  border: 1px solid #ccc;
  border-radius: 8px;
}
</style>
